package com.ruoyi.common.utils.file.transfer;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 远程文件传输工具类 scp
 *
 * @author ysz
 * @date 2024/6/20 16:52
 */
public class ScpTransferUtil implements FileTransferUtils{
    private static final Logger log = LoggerFactory.getLogger(ScpTransferUtil.class);
    Connection conn;

    /**
     * 获取连接
     **/
    @Override
    public boolean getConnection(TransferConnectEntity transferConnectEntity) {
        try {
            conn = new Connection(transferConnectEntity.getIp(), transferConnectEntity.getPort());
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(transferConnectEntity.getUsername(),
                    transferConnectEntity.getPassword());
            if (isAuthenticated == false) {
                log.error("登录失败");
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 获取远程文件
     */
    @Override
    public boolean getFile(TransferConnectEntity transferConnectEntity, String remotePath, String remoteFile, String localPath) {
        getConnection(transferConnectEntity);
        try {
            SCPClient client = new SCPClient(conn);
            client.get(remotePath + "/" + remoteFile, localPath);
        } catch (IOException e) {
            log.error(e.getMessage());
            return false;
        } finally {
            // 关闭通道
            if (conn != null) {
                conn.close();
            }
        }
        return true;
    }

    /**
     * 远程上传文件
     */
    @Override
    public boolean putFile(TransferConnectEntity transferConnectEntity, String localFile, String remotePath) {
        getConnection(transferConnectEntity);
        try {
            SCPClient client = new SCPClient(conn);
            client.put(localFile, remotePath);
        } catch (IOException e) {
            log.error(e.getMessage());
            return false;
        } finally {
            // 关闭通道
            if (conn != null) {
                conn.close();
            }
        }
        return true;
    }

    @Override
    public boolean putFiles(TransferConnectEntity transferConnectEntity, String localPath, String remotePath) {
        getConnection(transferConnectEntity);
        try {
            File file = new File(localPath);
            File[] files = file.listFiles();
            SCPClient client = new SCPClient(conn);
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                    client.put(Files.readAllBytes(Paths.get(files[i].getPath())), files[i].getName(), remotePath);
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage());
            return false;
        } finally {
            // 关闭通道
            if (conn != null) {
                conn.close();
            }
        }
        return true;
    }

//    /**
//     * 远程上传文件并对上传文件重命名
//     * @param localFile 本地文件路径
//     *@param remoteFileName 远程文件名
//     * @param remoteTargetDirectory  远程存放文件路径
//     *@param mode 默认"0600"，length=4
//     */
//    public void putFile(String localFile, String remoteFileName,String remoteTargetDirectory,String mode) {
//        Connection conn = new Connection(ip,port);
//        try {
//            conn.connect();
//            boolean isAuthenticated = conn.authenticateWithPassword(username,
//                    password);
//            if (isAuthenticated == false) {
////                logger.log(Level.ERROR_INT,"authentication failed");
//            }
//            SCPClient client = new SCPClient(conn);
//            if((mode == null) || (mode.length() == 0)){
//                mode = "0600";
//            }
//            client.put(localFile, remoteFileName, remoteTargetDirectory, mode);
//
//            //重命名
//            Session sess = conn.openSession();
//            String tmpPathName = remoteTargetDirectory + File.separator+ remoteFileName;
//            String newPathName = tmpPathName.substring(0, tmpPathName.lastIndexOf("."));
//            sess.execCommand("mv " + remoteFileName + " " + newPathName);
//
//            conn.close();
//        } catch (IOException e) {
////            logger.log(Level.ERROR_INT,e.getMessage());
//        }
//    }

}
